from tdx.MyTT import *


def ths_chaodi(df,r=1):
    CLOSE = df.close.values;
    OPEN = df.open.values
    HIGH = df.high.values;
    LOW = df.low.values
    LC = REF(CLOSE, 1);
    RSI1 = SMA(MAX(CLOSE - LC, 0), 3, 1) / SMA(ABS(CLOSE - LC), 3, 1) * 100;
    RSI2 = SMA(MAX(CLOSE - LC, 0), 5, 1) / SMA(ABS(CLOSE - LC), 5, 1) * 100;
    RSI3 = SMA(MAX(CLOSE - LC, 0), 8, 1) / SMA(ABS(CLOSE - LC), 8, 1) * 100;
    相对强弱=0.5*RSI1+0.31*RSI2+0.19*RSI3;
    wave1 = SMA(100 * (CLOSE - LLV(LOW, 8)) / (HHV(HIGH, 8) - LLV(LOW, 8)), 3, 1);
    wave2 = SMA(100 * (CLOSE - LLV(LOW, 8)) / (HHV(HIGH, 8) - LLV(LOW, 8)), 5, 1);
    wave3 = SMA(100 * (CLOSE - LLV(LOW, 8)) / (HHV(HIGH, 8) - LLV(LOW, 8)), 8, 1);
    短线波段 = 0.5 * wave1 + 0.31 * wave2 + 0.19 * wave3;
    风险系数 = 0.5 * 相对强弱 + 0.5 * 短线波段;
    # 波段小于20, 股价翻红;
    if 风险系数[-1] < 20 and CLOSE[-1] > OPEN[-1] and r > 0:
        CD1 = 1
    else:
        CD1 = 0
    #波段小于20, 股价未翻红, 但未创新低
    if 风险系数[-1] < 20 and LOW[-1] >= REF(LOW, 1)[-1] and CLOSE[-1] > LOW[-1] and r > 0:
        CD2 = 1
    else:
        CD2 = 0
    # 前一日波段小于20, 今日转向;
    if REF(风险系数, 1)[-1] < 20 and 风险系数[-1] > REF(风险系数, 1)[-1]:
        CD3 = 1
    else:
        CD3 = 0
    SIGNALBUY = CD1==1 or CD2==1 or CD3==1
    # SIGNALBUY = True if (CD1==1 or CD2==1 or CD3==1) else False;
    X = (SIGNALBUY and COUNT(SIGNALBUY, 3) == 1);#三个交易日只提示一次
    return 风险系数,SIGNALBUY

def boll(data):
    df = pd.DataFrame(data, columns=["open", "close", "high", "low", "date", "jlr", "cje"])
    CLOSE = df.close.values;
    rs = BOLL(CLOSE)
    item = {}
    item['upper'] = rs[0].tolist()[19:]
    item['mid'] = rs[1].tolist()[19:]
    item['lower'] = rs[2].tolist()[19:]
    return item

def zlqx(df):
    CLOSE = df.close.values;
    OPEN = df.open.values
    HIGH = df.high.values;
    LOW = df.low.values
    VAR1 = REF((LOW + OPEN + CLOSE + HIGH) / 4, 1);
    VAR2 = SMA(ABS(LOW - VAR1), 13, 1) / SMA(MAX(LOW - VAR1, 0), 10, 1);
    VAR3 = EMA(VAR2, 10);
    VAR4 = LLV(LOW, 33);
    VAR5 = EMA(IF(LOW <= VAR4, VAR3, 0), 3);

    主力进场= IF(VAR5 > REF(VAR5, 1), VAR5, 0)
    洗盘= IF(VAR5 < REF(VAR5, 1), VAR5, 0)

    data = []
    for index,v in enumerate(主力进场):
        item = {}
        item['zlqxtype'] = 0
        item['zlqx'] = v
        if 洗盘[index] > 1.5:
            item['zlqxtype'] = 1
            item['zlqx'] = 洗盘[index]
        data.append(item)
    return data

def calculate_rsi(close, window=14):
    delta = close.diff()
    gain = delta.clip(lower=0)
    loss = -delta.clip(upper=0)
    avg_gain = gain.rolling(window).mean()
    avg_loss = loss.rolling(window).mean()
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))